/**
 * 公共工具函数
 */

// Element UI 消息实例
let messageInstance = null;
let loadingInstance = null;

/**
 * 获取当前页面的vue实例（用于调用Element UI组件）
 */
const getCurrentPageVue = () => {
	const pages = getCurrentPages();
	const currentPage = pages[pages.length - 1];
	return currentPage ? currentPage.$vm : null;
};

/**
 * 显示成功消息
 */
export const showSuccess = (title, duration = 1500) => {
	const vm = getCurrentPageVue();
	if (vm && vm.$message) {
		vm.$message({
			message: title,
			type: 'success',
			duration: duration,
			showClose: true
		});
	} else {
		// 降级到uni-app原生提示
		uni.showToast({
			title: title,
			icon: 'success',
			duration: duration
		});
	}
};

/**
 * 显示错误消息
 */
export const showError = (title, duration = 3000) => {
	const vm = getCurrentPageVue();
	if (vm && vm.$message) {
		vm.$message({
			message: title,
			type: 'error',
			duration: duration,
			showClose: true
		});
	} else {
		// 降级到uni-app原生提示
		uni.showToast({
			title: title,
			icon: 'none',
			duration: duration
		});
	}
};

/**
 * 显示警告消息
 */
export const showWarning = (title, duration = 2500) => {
	const vm = getCurrentPageVue();
	if (vm && vm.$message) {
		vm.$message({
			message: title,
			type: 'warning',
			duration: duration,
			showClose: true
		});
	} else {
		// 降级到uni-app原生提示
		uni.showToast({
			title: title,
			icon: 'none',
			duration: duration
		});
	}
};

/**
 * 显示信息消息
 */
export const showInfo = (title, duration = 2000) => {
	const vm = getCurrentPageVue();
	if (vm && vm.$message) {
		vm.$message({
			message: title,
			type: 'info',
			duration: duration,
			showClose: true
		});
	} else {
		// 降级到uni-app原生提示
		uni.showToast({
			title: title,
			icon: 'none',
			duration: duration
		});
	}
};

/**
 * 显示加载中
 */
export const showLoading = (title = '加载中...') => {
	const vm = getCurrentPageVue();
	if (vm && vm.$loading) {
		// 关闭之前的loading
		hideLoading();
		
		loadingInstance = vm.$loading({
			lock: true,
			text: title,
			spinner: 'el-icon-loading',
			background: 'rgba(0, 0, 0, 0.7)'
		});
	} else {
		// 降级到uni-app原生提示
		uni.showLoading({
			title: title,
			mask: true
		});
	}
};

/**
 * 隐藏加载
 */
export const hideLoading = () => {
	if (loadingInstance) {
		loadingInstance.close();
		loadingInstance = null;
	} else {
		// 降级到uni-app原生方法
		uni.hideLoading();
	}
};

/**
 * 确认对话框
 */
export const showConfirm = (content, title = '提示', confirmButtonText = '确定', cancelButtonText = '取消') => {
	return new Promise((resolve, reject) => {
		const vm = getCurrentPageVue();
		if (vm && vm.$confirm) {
			vm.$confirm(content, title, {
				confirmButtonText: confirmButtonText,
				cancelButtonText: cancelButtonText,
				type: 'warning',
				center: true,
				closeOnClickModal: false,
				distinguishCancelAndClose: true
			}).then(() => {
				resolve(true);
			}).catch(() => {
				reject(false);
			});
		} else {
			// 降级到uni-app原生方法
			uni.showModal({
				title: title,
				content: content,
				confirmText: confirmButtonText,
				cancelText: cancelButtonText,
				success: (res) => {
					if (res.confirm) {
						resolve(true);
					} else {
						reject(false);
					}
				}
			});
		}
	});
};

/**
 * 输入对话框
 */
export const showInput = (content, title = '请输入', placeholder = '') => {
	return new Promise((resolve, reject) => {
		const vm = getCurrentPageVue();
		if (vm && vm.$prompt) {
			vm.$prompt(content, title, {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				inputPlaceholder: placeholder,
				inputValidator: (value) => {
					if (!value || !value.trim()) {
						return '输入内容不能为空';
					}
					return true;
				},
				inputErrorMessage: '输入内容不能为空',
				center: true,
				closeOnClickModal: false
			}).then(({ value }) => {
				resolve(value.trim());
			}).catch(() => {
				reject(null);
			});
		} else {
			// 降级到uni-app原生方法
			uni.showModal({
				title: title,
				content: content,
				editable: true,
				placeholderText: placeholder,
				success: (res) => {
					if (res.confirm && res.content && res.content.trim()) {
						resolve(res.content.trim());
					} else {
						reject(null);
					}
				}
			});
		}
	});
};

/**
 * 格式化文件大小
 */
export const formatFileSize = (bytes) => {
	if (!bytes || bytes === 0) return '0B';
	if (bytes < 1024) return bytes + 'B';
	if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + 'KB';
	return (bytes / (1024 * 1024)).toFixed(1) + 'MB';
};

/**
 * 格式化时长（秒转换为 mm:ss）
 */
export const formatDuration = (seconds) => {
	if (!seconds || seconds === 0) return '0:00';
	const min = Math.floor(seconds / 60);
	const sec = seconds % 60;
	return `${min}:${sec.toString().padStart(2, '0')}`;
};

/**
 * 格式化日期时间
 */
export const formatDateTime = (timestamp) => {
	if (!timestamp) return '';
	const date = new Date(timestamp);
	return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
};

/**
 * 格式化日期
 */
export const formatDate = (timestamp) => {
	if (!timestamp) return '';
	const date = new Date(timestamp);
	return date.toLocaleDateString();
};

/**
 * 错误处理
 */
export const handleError = (error, defaultMessage = '操作失败') => {
	console.error('Error:', error);
	const message = error.message || error || defaultMessage;
	showError(message);
	return message;
};

/**
 * 验证文件类型
 */
export const validateFileType = (fileName, allowedTypes = ['mp3', 'wav', 'm4a', 'aac']) => {
	const ext = fileName.toLowerCase().split('.').pop();
	return allowedTypes.includes(ext);
};

/**
 * 验证文件大小
 */
export const validateFileSize = (fileSize, maxSize = 50 * 1024 * 1024) => { // 默认50MB
	return fileSize <= maxSize;
};

/**
 * 获取文件扩展名
 */
export const getFileExtension = (fileName) => {
	return fileName.toLowerCase().split('.').pop();
};

/**
 * 获取不带扩展名的文件名
 */
export const getFileNameWithoutExtension = (fileName) => {
	return fileName.replace(/\.[^/.]+$/, "");
};

/**
 * 防抖函数
 */
export const debounce = (func, wait) => {
	let timeout;
	return function executedFunction(...args) {
		const later = () => {
			clearTimeout(timeout);
			func(...args);
		};
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);
	};
};

/**
 * 节流函数
 */
export const throttle = (func, limit) => {
	let inThrottle;
	return function() {
		const args = arguments;
		const context = this;
		if (!inThrottle) {
			func.apply(context, args);
			inThrottle = true;
			setTimeout(() => inThrottle = false, limit);
		}
	}
};
